package com.哈希表;

import java.util.LinkedList;

class MyHashSet2 {
    private Bucket2[] bucketArray;
    private int keyRange;

    /** Initialize your data structure here. */
    public MyHashSet2() {
        this.keyRange = 769;
        this.bucketArray = new Bucket2[this.keyRange];
        for (int i = 0; i < this.keyRange; ++i)
            this.bucketArray[i] = new Bucket2();
    }

    protected int _hash(int key) {
        return (key % this.keyRange);
    }

    public void add(int key) {
        int bucketIndex = this._hash(key);
        this.bucketArray[bucketIndex].insert(key);
    }

    public void remove(int key) {
        int bucketIndex = this._hash(key);
        this.bucketArray[bucketIndex].delete(key);
    }

    /** Returns true if this set contains the specified element */
    public boolean contains(int key) {
        int bucketIndex = this._hash(key);
        return this.bucketArray[bucketIndex].exists(key);
    }
    public String toString(){
        StringBuilder builder = new StringBuilder();
        for(int i = 0 ;i<bucketArray.length;i++){
            builder.append(String.format("键:%s,桶{",i));
            bucketArray[i].container.forEach(item->{
                builder.append(item).append(",");
            });
            builder.append("}").append("\n");

        }
        return builder.toString();
    }

    public static void main(String[] args) {
        MyHashSet2 hash = new MyHashSet2();
        hash.add(1);
        hash.add(2);
        hash.add(3);
     hash.add(98776);
       // System.out.println(hash.toString());
        System.out.println(hash.contains(3));
        hash.remove(1);
        System.out.println(hash.toString());
    }
}


class Bucket2 {
     LinkedList<Integer> container;

    public Bucket2() {
        container = new LinkedList<Integer>();
    }

    public void insert(Integer key) {
        int index = this.container.indexOf(key);
        if (index == -1) {
            this.container.addFirst(key);
        }
    }

    public void delete(Integer key) {
        this.container.remove(key);
    }

    public boolean exists(Integer key) {
        int index = this.container.indexOf(key);
        return (index != -1);
    }
}



